<script setup>
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue'
import { computed, ref } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const tableData = ref([
  { name: 'ABMF2024001', position: 'ABMF', startTime: '2004001', endTime: '2005002' },
  {
    name: 'ABMF2024002', position: 'ABMF', startTime: '2024002', endTime: '2005003'
  },
  { name: 'ABMF2024003', position: 'ABMF', startTime: '2024003', endTime: '20050101' },
  {
    name: 'ABPO2024001',
    position: 'ABPO',
    startTime: '2024006',
    endTime: '2005101'
  },
  { name: 'ABPO2024002', position: 'ABPO', startTime: '2024004', endTime: '2005001' },
  {
    name: 'ABPO2024003',
    position: 'ABPO',
    startTime: '2024005',
    endTime: '2005101'
  },])
const chartDom = ref(null)

const searchCondition = ref({
  currentPage: 1,
  pageSize: 5,
  name: '',
  time: [],
  position: ''
})

function formatDate(dateString) {
  // 取出年份和第几天
  const year = dateString.substring(0, 4);
  const dayOfYear = dateString.substring(4);

  // 创建一个新的日期对象
  const date = new Date(year, 0); // 月份是从0开始的，所以0代表一月

  // 将日期设置为年份的第几天
  date.setDate(dayOfYear);

  // 获取年份
  const formattedYear = date.getFullYear();

  // 获取月份（注意：getMonth() 返回的是从 0 开始的，即 0 表示一月，1 表示二月，依此类推）
  const formattedMonth = date.getMonth() + 1; // 加1是为了转换为实际的月份（1 到 12）

  // 获取日期
  const formattedDay = date.getDate();

  // 格式化日期字符串
  // 返回格式化后的日期字符串
  return `${formattedYear}-${formattedMonth < 10 ? '0' + formattedMonth : formattedMonth}-${formattedDay < 10 ? '0' + formattedDay : formattedDay}`;
}

// // 测试函数
console.log(formatDate("2024032")); // 输出：2024-01-01


const filteredData = computed(() => {
  let tempData = [...tableData.value]
  if (searchCondition.value.position !== '') {
    tempData = tempData.filter(item => item.position === searchCondition.value.position)
  }
  if(searchCondition.value.time.length!==0){
    const startTime=searchCondition.value.time[0]
    tempData=tempData.filter(item=>startTime<=formatDate(item.startTime))
  }
  return tempData

})
const total = computed(() => filteredData.value.length)

const ruleFormRef = ref(null)
const submitForm = (searchCondition) => {
  if (!ruleFormRef.value) return
  console.log('SearchCondition.vue-submitForm-searchCondition', searchCondition)

}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
const initBarChart = async (fileName = 'ABMF2024001') => {
  const res = await axios.get(`/api/result/${fileName}.json`)
  const barData = computed(() => res.data['SUMM']['OBS'])
  const myChart = echarts.init(chartDom.value)

  // 获取值的函数
  const getValue = (system, frequency) => {
    if (barData.value[system] && barData.value[system][frequency]) {
      return barData.value[system][frequency].RATZ
    }
    return null
  }

  // 获取颜色的函数
  const getColor = (system) => {
    const colorMap = {
      'GPS': 'red',
      'GAL': 'blue',
      'BDS': 'green',
      'GLO': 'yellow',
      'SBS': 'orange'
    }
    return colorMap[system]
  }

  const systemArray = ref([])
  const series = computed(() => {
    const data = []
    for (const system in barData.value) {
      for (const frequency in barData.value[system]) {
        systemArray.value.push(system)
        const value = getValue(system, frequency)
        if (value !== null) {
          const color = getColor(system)
          data.push({ value, itemStyle: { color } })
        }
      }
    }
    return data

  })

  /**
   *  处理数组，将连续的数据段合并为一个数组
   * @param arr
   * @returns {*[]}
   */
  function processArray (arr) {
    // 找到数组中的连续数据段
    const segments = []
    let currentNum = arr[0]
    let count = 0

    arr.forEach(num => {
      if (num === currentNum) {
        count++
      } else {
        segments.push({ num: currentNum, count })
        currentNum = num
        count = 1
      }
    })
    segments.push({ num: currentNum, count })

    // 初始化新数组
    const processedArray = []

    // 处理每个连续数据段
    segments.forEach(segment => {
      const { num, count } = segment
      const middleIndex = Math.floor(count / 2)
      let index = 0

      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === num) {
          if (index === middleIndex) {
            processedArray.push(num)
          } else {
            processedArray.push('')
          }
          index++
        }
      }
    })

    return processedArray
  }

// console.log('App.vue-initBarChart-processArray(series.value)',processArray(systemArray.value))

  console.log('App.vue-initBarChart-systemArray', ((systemArray.value)))
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },

    /*toolbox: {
      show: true,
      orient: 'vertical',
      left: 'right',
      top: 'center',
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['line', 'bar', 'stack'] },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    },*/
    xAxis: [
      {
        type: 'category',
        axisTick: { show: false },
        data: processArray(systemArray.value)
      }
    ],
    yAxis: [
      {
        type: 'value',

      }
    ],
    series: [
      {
        data: series.value,
        type: 'bar'
      }
    ]
  }
  option && myChart.setOption(option)
}


/**
 * 点击单元格重新渲染数据
 * @param cellValue
 */
const handleCellClick = (cellValue) => {
  console.log('App.vue-handleCellClick-cellValue', cellValue.name)
  initBarChart(`${cellValue.name}`)
}

</script>

<template>
  <el-container>
    <el-header>
      <el-button type="primary"
                 :icon="Search">数据质量检查
      </el-button>
      <el-button type="primary"
                 :icon="Delete">首页
      </el-button>
      <el-button type="primary"
                 :icon="Share">数据完整性
      </el-button>
      <el-button type="primary"
                 :icon="Upload">周跳
      </el-button>
      <el-button type="primary"
                 :icon="Edit">定位精度
      </el-button>
      <el-button type="primary"
                 :icon="Edit">信噪比
      </el-button>
    </el-header>
    <el-main>
      <div class="box-card">
        <div class="file-list">
          <div class="title">
            <el-button size="large"
                       :icon="Search">Search
            </el-button>
          </div>
          <div class="content">

            <el-table
                @cell-click="handleCellClick"
                border
                :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}"
                :data="filteredData.slice((searchCondition.currentPage-1)*searchCondition.pageSize,searchCondition.currentPage*searchCondition.pageSize)"
                style="width: 100%">
              <el-table-column
                  prop="name"
                  label="名称">
              </el-table-column>
              <el-table-column
                  prop="position"
                  label="测站">
              </el-table-column>
              <el-table-column
                  prop="startTime"
                  label="起始时间">
              </el-table-column>
              <el-table-column
                  prop="endTime"
                  label="终止时间">
              </el-table-column>
            </el-table>
            <el-pagination layout="prev, pager, next"
                           v-model:page-size="searchCondition.pageSize"
                           v-model:current-page="searchCondition.currentPage"
                           :total="total"/>
          </div>
        </div>
        <div class="search-condition">


          <div class="title">
            <el-button size="large"
                       :icon="Search">搜索条件
            </el-button>
          </div>
          <div class="content">
            <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="searchCondition"
                status-icon
                label-width="auto"
                class="demo-ruleForm"
            >
              <el-form-item label="测站"
                            prop="pass">
                <el-input v-model="searchCondition.position"
                          autocomplete="off"/>
              </el-form-item>
              <el-form-item label="搜索时间"
                            required>
                <el-date-picker
                    v-model="searchCondition.time"
                    type="daterange"
                    range-separator="To"
                    value-format="YYYY-MM-DD"
                    start-placeholder="起始时间"
                    end-placeholder="终止时间"
                />
              </el-form-item>
              <el-form-item label="频段"
                            prop="frequency">
                <el-input v-model.number="searchCondition.frequency"/>
              </el-form-item>
              <el-form-item label="系统"
                            prop="system">
                <el-input v-model.number="searchCondition.system"/>
              </el-form-item>
              <div style="display: flex;justify-content: center;">
                <el-button type="primary"
                           @click="submitForm(searchCondition)">
                  Submit
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
              </div>
            </el-form>
          </div>
        </div>

      </div>
    </el-main>
    <el-footer>
      <div class="box-card"
           ref="chartDom">

      </div>
    </el-footer>
  </el-container>
</template>

<style scoped
       lang="less">
.flex(@justify-content:center;@align-items:center;) {
  display: flex;
  justify-content: @justify-content;
  align-items: @align-items;
}

.el-container {
  width: 100%;
  height: 100vh;

  .el-header {
    width: 100%;
    height: 8%;
    background-color: blue;
    .flex();
  }

  .el-main {
    width: 100%;
    height: 35%;
    box-sizing: border-box;
    padding: 0 5rem;

    .box-card {
      height: 100%;
      .flex(center, start);
      gap: 20px;

      .file-list {
        gap: .5rem;
        flex: 1;


        .title {
          padding: .5rem 0;
        }
      }

      .search-condition {
        flex: 1;
        gap: .5rem;

        .title {
          padding: .5rem 0;
        }

      }

    }
  }

  .el-footer {
    width: 100%;
    box-sizing: border-box;
    height: 47%;

    .box-card {
      width: 100%;
      height: 100%;
    }
  }
}
</style>


